﻿using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine(EstimatePi(10000));
        }

        static double EstimatePi(int trials)
        {
            return Math.Sqrt(6/RandomGcdTest(trials, 0));
        }

        static double RandomGcdTest(int trials, int initialX)
        {
            return RandomGcdTestIter(trials, trials, 0, initialX);
        }

        static double RandomGcdTestIter(int trials, int trialsRemaining, int trialsPassed, int x)
        {
            if (trialsRemaining == 0) return (double) trialsPassed/trials;
            var x1 = RandUpdate(x);
            var x2 = RandUpdate(x1);
            var passed = Gcd(x1, x2) == 1 ? trialsPassed + 1 : trialsPassed;
            return RandomGcdTestIter(trials, trialsRemaining - 1, passed, x2);
        }

        static int RandUpdate(int x)
        {
            const int a = 27;
            const int b = 26;
            const int m = 127;
            return (a*x + b)%m;
        }

        static int Gcd(int a, int b)
        {
            return b == 0 ? a : Gcd(b, a % b);
        }
    }
}